package com.qqpz.sign_project.service.impl;

import com.aliyun.facebody20191230.Client;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.google.gson.Gson;
import com.qqpz.sign_project.service.ApiService;
import org.springframework.stereotype.Service;
import com.aliyun.tea.*;
import com.aliyun.facebody20191230.*;
import com.aliyun.facebody20191230.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApiServiceImpl implements ApiService {
    @Override
    public Map<String, Object> getOssToken() {
        //创建返回map
        Map<String, Object> map=new HashMap<>();
        // STS接入地址，例如sts.cn-hangzhou.aliyuncs.com。
        String endpoint = "sts.cn-shanghai.aliyuncs.com";
        // 填写步骤1生成的访问密钥AccessKey ID和AccessKey Secret。
        String AccessKeyId = "LTAI4G54qwUQJxwfNkxyvQcw";
        String accessKeySecret = "CpZKsOLjFNfhrA8nUzwmZQK7aumAZb";
        // 填写步骤3获取的角色ARN。
        String roleArn = "acs:ram::1581393617162765:role/ramosstest";
        // 自定义角色会话名称，用来区分不同的令牌，例如可填写为SessionTest。
        String roleSessionName = "SessionTest";
        // 以下Policy用于限制仅允许使用临时访问凭证向目标存储空间examplebucket上传文件。
        // 临时访问凭证最后获得的权限是步骤4设置的角色权限和该Policy设置权限的交集，即仅允许将文件上传至目标存储空间examplebucket下的exampledir目录。
        String policy = "{\n" +
                "    \"Version\": \"1\", \n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"oss:PutObject\"\n" +
                "            ], \n" +
                "            \"Resource\": [\n" +
                "                \"acs:oss:*:*:sign-face/*\" \n" +
                "            ], \n" +
                "            \"Effect\": \"Allow\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        try {
            // 添加endpoint。
            DefaultProfile.addEndpoint("", "oss-cn-shanghai", "Sts", endpoint);
            // 构造default profile。
            IClientProfile profile = DefaultProfile.getProfile("oss-cn-shanghai", AccessKeyId, accessKeySecret);
            // 构造client。
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy); // 如果policy为空，则用户将获得该角色下所有权限。
            request.setDurationSeconds(3600L); // 设置临时访问凭证的有效时间为3600秒。
            final AssumeRoleResponse response = client.getAcsResponse(request);
            map.put("Expiration",response.getCredentials().getExpiration());
            map.put("AccessKeyId",response.getCredentials().getExpiration());
            map.put("AccessKeySecret",response.getCredentials().getAccessKeySecret());
            map.put("SecurityToken",response.getCredentials().getSecurityToken());
            map.put("RequestId",response.getRequestId());
            System.out.println("Expiration: " + response.getCredentials().getExpiration());
            System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
            System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
            System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
            System.out.println("RequestId: " + response.getRequestId());
        } catch (ClientException e) {
            System.out.println("Failed：");
            System.out.println("Error code: " + e.getErrCode());
            System.out.println("Error message: " + e.getErrMsg());
            System.out.println("RequestId: " + e.getRequestId());
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addFace(String url, String id) throws Exception{
        int i;
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId("LTAI4G54qwUQJxwfNkxyvQcw")
                // 您的AccessKey Secret
                .setAccessKeySecret("CpZKsOLjFNfhrA8nUzwmZQK7aumAZb");
                // 访问的域名
        config.endpoint = "facebody.cn-shanghai.aliyuncs.com";
            Client client = new Client(config);
            AddFaceEntityRequest entityRequest = new AddFaceEntityRequest();
            entityRequest.setDbName("default").setEntityId(id);
            client.addFaceEntity(entityRequest);
            AddFaceRequest request = new AddFaceRequest();
            request.setDbName("default");
            request.setImageUrl(url);
            request.setEntityId(id);
            AddFaceResponse response = client.addFace(request);
            System.out.println(new Gson().toJson(response.getBody()));
            i=1;
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int searchFace(String url,String id) throws Exception{
        int i=0;
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId("LTAI4G54qwUQJxwfNkxyvQcw")
                // 您的AccessKey Secret
                .setAccessKeySecret("CpZKsOLjFNfhrA8nUzwmZQK7aumAZb");
        // 访问的域名
        config.endpoint = "facebody.cn-shanghai.aliyuncs.com";
            Client client = new Client(config);
            SearchFaceRequest request = new SearchFaceRequest();
            request.setDbName("default");
            request.setImageUrl(url);
            request.setLimit(1);
            SearchFaceResponse response = client.searchFace(request);
            String entityId=response.getBody().getData().getMatchList().get(0).getFaceItems().get(0).getEntityId();
            if(entityId.equals(id)&&response.getBody().getData().getMatchList().get(0).getFaceItems().get(0).getScore()>0.6){
                i=1;
            }
            System.out.println(new Gson().toJson(response.getBody()));
        return i;
    }

    @Override
    public int deleteFace(String id) throws Exception{
        int i=0;
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId("LTAI4G54qwUQJxwfNkxyvQcw")
                // 您的AccessKey Secret
                .setAccessKeySecret("CpZKsOLjFNfhrA8nUzwmZQK7aumAZb");
        // 访问的域名
        config.endpoint = "facebody.cn-shanghai.aliyuncs.com";
        Client client = new Client(config);
        DeleteFaceEntityRequest request = new DeleteFaceEntityRequest();
        request.setDbName("default").setEntityId(id);
        DeleteFaceEntityResponse response = client.deleteFaceEntity(request);
        System.out.println(new Gson().toJson(response.getBody()));
        i=1;
        return i;
    }

}
